package com.ty.day6.home;

import com.ty.day5.home.IOUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 *
 * @author : txy
 * @create : 2023/11/29 17:53
 */
public class Task2 {
    public static void main(String[] args) {
        copy(new File("D:\\flower.png"),new File("e:\\img"));
    }
    public static void copy(File from, File to) {
        //判断传递的参数是否为null或目标文件不存在
        if (from == null || to == null || !from.exists()) {
            System.out.println("文件路径不存在，或者是null");
            return;
        }
        //目标目录不存在就创建
        if(!to.exists()){
            to.mkdirs();
        }
        //目标时目录就获取源文件的文件名
        if (to.isDirectory()){
            to=new File(to.getPath()+"\\"+from.getName());
        }

        System.out.println("正在复制" + from.getPath());
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            //创建文件输入输出流
            fis = new FileInputStream(from);
            fos = new FileOutputStream(to);
            //读取文件数据
            byte[] bytes = new byte[1024];
            //获得长度
            int len = fis.read(bytes);
            while (len != -1) {
                //将字节写入
                fos.write(bytes, 0, len);
                //再次读取
                len = fis.read(bytes);
            }
            System.out.println("复制完成!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭输入流
                if (fis != null) {
                    fis.close();
                }
                //关闭输出流
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
